package com.youme.viewmodel

import android.annotation.SuppressLint
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.salton123.utils.RxCompat
import com.youme.*
import com.youme.api.Callback
import com.youme.api.TokenInterceptor
import com.youme.api.YouMeApi
import com.youme.base.Ret
import com.youme.base.RetDef
import com.youme.model.*
import com.youme.model.param.*
import com.youme.model.result.Resp
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import kotlin.coroutines.resume

/**
 * @Time:2021/3/16 10:03
 * @Author:wujinsheng
 * @Description:
 */
@SuppressLint("CheckResult")
open class YouMeApiViewModel : ViewModel(), YouMeApi.Order by mOrder, YouMeApi.FriendCircle by mFriendCircle {

    var mAddressId: String = ""
    fun reg(code: String, password: String, phonenumber: String, userName: String, callback: Callback<Boolean>) {
        mUserApi.reg(code, password, phonenumber, userName).compose(RxCompat.schedulersTransformer()).subscribe({
            if (it.code == 200) {
                callback.onSuccess(true)
            } else {
                callback.onFailed(errorCode = it.code, errorMessage = it.msg)
            }
        }, {
            callback.onFailed(errorCode = -1, errorMessage = "请求异常", throwable = it)
        })
    }

    private fun code(phone: String, type: Int, callback: Callback<Boolean>) {
        mUserApi.code(phone, type).compose(RxCompat.schedulersTransformer()).subscribe({
            if (it.code == 200) {
                callback.onSuccess(true)
            } else {
                callback.onFailed(errorCode = it.code, errorMessage = it.msg)
            }
        }, {
            callback.onFailed(errorCode = -1, errorMessage = "请求异常", throwable = it)
        })
    }

    suspend fun regCode(phone: String): RetDef {
        return suspendCancellableCoroutine { continuation ->
            code(phone, 2, object : Callback<Boolean> {
                override fun onFailed(errorCode: Int, errorMessage: String, throwable: Throwable?) {
                    continuation.resume(Ret.Failure(errorCode, errorMessage, throwable))
                }

                override fun onSuccess(value: Boolean) {
                    continuation.resume(Ret.Success(Unit))
                }
            })
        }
    }

    suspend fun loginCode(phone: String): RetDef {
        return suspendCancellableCoroutine { continuation ->
            code(phone, 1, object : Callback<Boolean> {
                override fun onFailed(errorCode: Int, errorMessage: String, throwable: Throwable?) {
                    continuation.resume(Ret.Failure(errorCode, errorMessage, throwable))
                }

                override fun onSuccess(value: Boolean) {
                    continuation.resume(Ret.Success(Unit))
                }
            })
        }
    }

    fun formLogin(username: String, password: String, callback: Callback<Boolean>) {
        mUserApi.formLogin(username, password)
            .compose(RxCompat.schedulersTransformer())
            .subscribe({
                if (it.code == 200) {
                    TokenInterceptor.updateToken(it.data)
                    callback.onSuccess(true)
                } else {
                    callback.onFailed(errorCode = it.code, errorMessage = it.msg)
                }
            }, {
                callback.onFailed(errorCode = -1, errorMessage = "请求异常", throwable = it)
            })
    }

    suspend fun mobileLogin(code: String, phonenumber: String): Ret<String> {
        return suspendCancellableCoroutine { continuation ->
            mUserApi.mobileLogin(ParamCodeLogin(code, phonenumber).toBody())
                .compose(RxCompat.schedulersTransformer())
                .subscribe({
                    if (it.code == 200) {
                        TokenInterceptor.updateToken(it.data)
                        continuation.resume(Ret.Success(it.msg))
                    } else {
                        continuation.resume(Ret.Failure(it.code, "请求异常"))
                    }
                }, {
                    continuation.resume(Ret.Failure(-1, "请求异常", it))
                })
        }
    }

    suspend fun register(code: String, password: String, phonenumber: String, userName: String): Ret<String> {
        return suspendCancellableCoroutine { continuation ->
            mUserApi.reg(code, password, phonenumber, userName)
                .compose(RxCompat.schedulersTransformer())
                .subscribe({
                    if (it.code == 200) {
                        TokenInterceptor.updateToken(it.msg)
                        continuation.resume(Ret.Success(it.msg))
                    } else {
                        continuation.resume(Ret.Failure(it.code, "请求异常"))
                    }
                }, {
                    continuation.resume(Ret.Failure(-1, "请求异常", it))
                })
        }
    }

    fun profile(callback: Callback<Profile>) {
        mUserApi.profile()
            .compose(RxCompat.schedulersTransformer())
            .subscribe({
                if (it.code == 200) {
                    callback.onSuccess(it.data)
                } else {
                    callback.onFailed(errorCode = it.code, errorMessage = it.msg)
                }
            }, {
                callback.onFailed(errorCode = -1, errorMessage = "请求异常", throwable = it)
            })
    }

    fun editProfile(profile: Profile, callback: Callback<Boolean>) {
        mUserApi.editProfile(profile.toBody())
            .compose(RxCompat.schedulersTransformer())
            .subscribe({
                if (it.code == 200) {
                    callback.onSuccess(true)
                } else {
                    callback.onFailed(errorCode = it.code, errorMessage = it.msg)
                }
            }, {
                callback.onFailed(errorCode = -1, errorMessage = "请求异常", throwable = it)
            })
    }

    fun listCateen(param: ParamCateen, callback: Callback<List<Rest>>) {
        mYouMeApi.listCateen(param.toBody())
            .compose(RxCompat.schedulersTransformer())
            .subscribe({
                if (it.code == 200) {
                    println(it.data)
                    callback.onSuccess(it.data)
                } else {
                    callback.onFailed(errorCode = it.code, errorMessage = it.msg)
                }
            }, {
                callback.onFailed(errorCode = -1, errorMessage = "请求异常", throwable = it)
            })
    }
    fun orderFrom(param: OrderForm, callback: Callback<List<String>>) {
//         mOrder.createOrder(param.toBody())
//                .compose(RxCompat.schedulersTransformer())
//                .subscribe({
//                    if (it.code == 200) {
//                        println(it.data)
//                        callback.onSuccess(it.data)
//                    } else {
//                        callback.onFailed(errorCode = it.code, errorMessage = it.msg)
//                    }
//                }, {
//                    callback.onFailed(errorCode = -1, errorMessage = "请求异常", throwable = it)
//                })
    }
    fun listSearch(param: SearchCateen, callback: Callback<List<Rest>>) {
        mYouMeApi.listSearch(param.toBody())
            .compose(RxCompat.schedulersTransformer())
            .subscribe({
                if (it.code == 200) {
                    println(it.data)
                    callback.onSuccess(it.data)
                } else {
                    callback.onFailed(errorCode = it.code, errorMessage = it.msg)
                }
            }, {
                callback.onFailed(errorCode = -1, errorMessage = "请求异常", throwable = it)
            })
    }
    fun listProduct(resid: String, callback: Callback<ProductDetail>) {
        mProduct.list(resid)
            .compose(RxCompat.schedulersTransformer())
            .subscribe({
                if (it.code == 200) {
                    println(it.data)
                    callback.onSuccess(it.data)
                } else {
                    callback.onFailed(errorCode = it.code, errorMessage = it.msg)
                }
            }, {
                callback.onFailed(errorCode = -1, errorMessage = "请求异常", throwable = it)
            })
    }

    fun roomList(resid: String, type :Int ,callback: Callback<List<Room>>) {
        mProduct.roomList(resid,type)
            .compose(RxCompat.schedulersTransformer())
            .subscribe({
                if (it.code == 200) {
                    println(it.data)
                    callback.onSuccess(it.data)
                } else {
                    callback.onFailed(errorCode = it.code, errorMessage = it.msg)
                }
            }, {
                callback.onFailed(errorCode = -1, errorMessage = "请求异常", throwable = it)
            })
    }

    fun newProduct(callback: Callback<List<Food>>) {
        mShouYe.newProduct()
            .compose(RxCompat.schedulersTransformer())
            .subscribe({
                if (it.code == 200) {
                    callback.onSuccess(it.data)
                } else {
                    callback.onFailed(errorCode = it.code, errorMessage = it.msg)
                }
            }, {
                callback.onFailed(errorCode = -1, errorMessage = "请求异常", throwable = it)
            })
    }
    fun getHotSale(lan: String, lon :String ,callback: Callback<List<Rest>>) {
        mShouYe.getHotSale(lan,lon)
            .compose(RxCompat.schedulersTransformer())
            .subscribe({
                if (it.code == 200) {
                    callback.onSuccess(it.data)
                } else {
                    callback.onFailed(errorCode = it.code, errorMessage = it.msg)
                }
            }, {
                callback.onFailed(errorCode = -1, errorMessage = "请求异常", throwable = it)
            })
    }
    fun getList(lan: String,callback: Callback<List<FoodAdd>>) {
        mTeamwork.list(lan)
            .compose(RxCompat.schedulersTransformer())
            .subscribe({
                if ( it.code == 200) {
                    callback.onSuccess(it.data)
                } else {
                    callback.onFailed(errorCode = it.code, errorMessage = it.msg)
                }
            }, {
                callback.onFailed(errorCode = -1, errorMessage = "请求异常", throwable = it)
            })
    }

    suspend fun saveAddress(
        receiverName: String, receiverMobile: String, receiverProvince: String,
        receiverCity: String, receiverDistrict: String,
        receiverAddress: String, checked: Boolean
    ): Ret<Boolean> {
        return suspendCancellableCoroutine { continuation ->
            mAddress.addAddress(
                ParamAddress(id = "",
                    receiverProvince = receiverProvince,
                    receiverCity = receiverCity,
                    receiverDistrict = receiverDistrict,
                    receiverAddress = receiverAddress,
                    receiverMobile = receiverMobile,
                    receiverName = receiverName,
                    isDefault = 0
                ).toBody())
                .compose(RxCompat.schedulersTransformer())
                .subscribe({
                    if (it.code == 200) {
                        continuation.resume(Ret.Success(true))
                    } else {
                        continuation.resume(Ret.Failure(it.code, "请求异常"))
                    }
                }, {
                    continuation.resume(Ret.Failure(-1, "请求异常", it))
                })
        }
    }

    suspend fun getDefaultAddress(): Ret<ParamAddress> {
        return suspendCancellableCoroutine { continuation ->
            if (mAddressId.isNullOrEmpty()) {
                continuation.resume(Ret.Failure(-1, "请求异常"))
            } else {
                mAddress.getAddressByUid(mAddressId)
                    .compose(RxCompat.schedulersTransformer())
                    .subscribe({
                        if (it.code == 200) {
                            continuation.resume(Ret.Success(it.data))
                        } else {
                            continuation.resume(Ret.Failure(it.code, "请求异常"))
                        }
                    }, {
                        continuation.resume(Ret.Failure(-1, "请求异常", it))
                    })
            }
        }
    }

    suspend fun listAddr(): Ret<List<ParamAddress>> {
        return suspendCancellableCoroutine { continuation ->
            mAddress.list()
                .compose(RxCompat.schedulersTransformer())
                .subscribe({
                    if (it.code == 200) {
                        continuation.resume(Ret.Success(it.data))
                    } else {
                        continuation.resume(Ret.Failure(it.code, "请求异常"))
                    }
                }, {
                    continuation.resume(Ret.Failure(-1, "请求异常", it))
                })
        }
    }
    suspend fun addFood(param: ParamAddFood)  : RetDef {
        return suspendCancellableCoroutine { continuation ->
            mTeamwork.add(param.toBody())
                .compose(RxCompat.schedulersTransformer())
                .subscribe({
                    if (it.code == 200) {
                        continuation.resume(Ret.Success(Unit))
                    } else {
                        continuation.resume(Ret.Failure(it.code, "请求异常"))
                    }
                }, {
                    continuation.resume(Ret.Failure(-1, "请求异常", it))
                })
        }
    }
    suspend fun deleteAddress(id: String): RetDef {
        return suspendCancellableCoroutine { continuation ->
            mAddress.deleteAddressByUid(id)
                .compose(RxCompat.schedulersTransformer())
                .subscribe({
                    if (it.code == 200) {
                        continuation.resume(Ret.Success(Unit))
                    } else {
                        continuation.resume(Ret.Failure(it.code, "请求异常"))
                    }
                }, {
                    continuation.resume(Ret.Failure(-1, "请求异常", it))
                })
        }
    }



    suspend fun shareFoodTest(): RetDef {
        return suspendCancellableCoroutine { continuation ->
            viewModelScope.launch {
                uploadImage("/sdcard/01.jpg").apply {
                    if (getOrNull().isNullOrEmpty()) {
                        continuation.resume(Ret.Failure(-1, "图片上传失败"))
                    } else {
                        val location = "山西省太原市"
                        val title = "生活不止有诗和远方，还有眼前的早餐"
                        val content =
                            "早饭吃饱饱，我是王饱饱！世界各地的早餐食品均有不同，通常都以谷类食物为主，配上牛奶、咖啡、粥等。早餐不建议吃腌的食物，因为腌的食物中可能存在着危险的物质——亚硝胺，会导致一些食道、肝的疾病。"
                        mFriendCircle.send(
                            ReqParam.MomentPublication(content, location,
                                this.getOrNull() ?: "",
                                title).toBody()).body()
                            ?.apply {
                                if (code == 200) {
                                    continuation.resume(Ret.Success(Unit))
                                } else {
                                    continuation.resume(Ret.Failure(code, "请求异常"))
                                }
                            }
                    }

                }
            }
        }
    }

    suspend fun uploadImage(filePath: String): Ret<String> {
        return suspendCancellableCoroutine { continuation ->
            val file = File(filePath)
            if (!file.exists()) {
                continuation.resume(Ret.Failure(-1, "文件不存在"))
            } else {
                val requestFile: RequestBody = file.asRequestBody("multipart/form-data".toMediaType())
                val body: MultipartBody.Part = MultipartBody.Part.createFormData("file", file.name, requestFile)
                viewModelScope.launch {
                    mYouMeApi.upload(body).body()?.apply {
                        if (code == 200) {
                            continuation.resume(Ret.Success(data))
                        } else {
                            continuation.resume(Ret.Failure(code, "请求异常"))
                        }
                    }
                }
            }
        }
    }

    /**
     * 阿里支付
     */
    suspend fun alipay(amount: Double, orderId: String): Ret<String> {
        return suspendCancellableCoroutine { continuation ->
            viewModelScope.launch {
                mYouMeApi.createAliPay(amount, orderId, "ALIPAY_APP").body()?.apply {
                    if (code == 200) {
                        continuation.resume(Ret.Success(data))
                    } else {
                        continuation.resume(Ret.Failure(code, "请求异常"))
                    }
                }
            }
        }
    }

    /**
     * 退款
     */
    suspend fun refundAlipay(amount: Double, orderAmount: Double, orderId: String): Ret<String> {
        return suspendCancellableCoroutine { continuation ->
            viewModelScope.launch {
                mYouMeApi.refund(amount, orderAmount, orderId, "ALIPAY_APP").body()?.apply {
                    if (code == 200) {
                        continuation.resume(Ret.Success(data))
                    } else {
                        continuation.resume(Ret.Failure(code, "请求异常"))
                    }
                }
            }
        }
    }

    /**
     * 微信支付
     */
    suspend fun wechatpay(amount: Double, orderId: String): Ret<Resp.WeChatPayResp> {
        return suspendCancellableCoroutine { continuation ->
            viewModelScope.launch {
                mYouMeApi.createWeChatPay(amount, orderId, "WXPAY_APP").body()?.apply {
                    if (code == 200) {
                        continuation.resume(Ret.Success(data))
                    } else {
                        continuation.resume(Ret.Failure(code, "请求异常"))
                    }
                }
            }
        }
    }

    /**
     * 微信退款
     */
    suspend fun refundWechatpay(amount: Double, orderAmount: Double, orderId: String): Ret<String> {
        return suspendCancellableCoroutine { continuation ->
            viewModelScope.launch {
                mYouMeApi.refund(amount, orderAmount, orderId, "WXPAY_APP").body()?.apply {
                    if (code == 200) {
                        continuation.resume(Ret.Success(data))
                    } else {
                        continuation.resume(Ret.Failure(code, "请求异常"))
                    }
                }
            }
        }
    }
}